package com.lsl.rdf.config;

import com.lsl.rdf.advice.LogAdvice;
import com.lsl.rdf.callback.LogAdviceCallback;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * Created by lsl on 2021/6/21.
 */
@Slf4j
@Component
public class LogAdviceConfig {
    private static final String userApiLogExpression = "execution(* com.lsl.rdf.api.impl.*..*(..))";

    @Value("${spring.application.name:unknown-application}")
    private String applicationName;

    @Value("${server.port:8080}")
    private String applicationPort;

    @Autowired(required = false)
    private LogAdviceCallback logAdviceCallback;
    @Autowired
    private LogProperties logProperties;

    @Bean
    @ConditionalOnProperty(prefix = "rdf.log", name = "enableLog", havingValue = "true", matchIfMissing = true)
    public AspectJExpressionPointcutAdvisor logPointcutAdvisor() {
        String expression = userApiLogExpression + (StringUtils.isBlank(logProperties.getLogExpression()) ? ""
                : " || " + logProperties.getLogExpression());

        AspectJExpressionPointcutAdvisor logPointcutAdvisor = new AspectJExpressionPointcutAdvisor();
        logPointcutAdvisor.setExpression(expression);
        logPointcutAdvisor.setAdvice(new LogAdvice(logProperties.getPrintLogPattern(), applicationName, applicationPort, logAdviceCallback));
        log.info("[RDF-COMPONENT-LOG] AspectJExpressionPointcutAdvisor initialization completed.");
        return logPointcutAdvisor;
    }
}
